package guda.mrpc.core.transport.tcp;

import guda.mrpc.core.RpcRequest;
import guda.mrpc.core.RpcResponse;
import guda.mrpc.core.server.ServiceProviderContainer;
import guda.mrpc.core.transport.callback.ResponseCallback;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by well on 17/5/23.
 */
public class TcpResponseCallback  extends ResponseCallback<Boolean> {

    public static final Logger log = LoggerFactory.getLogger(TcpResponseCallback.class);

    public TcpResponseCallback(ChannelHandlerContext ctx,RpcRequest request, ServiceProviderContainer serviceProviderContainer) {
        super(ctx, request, serviceProviderContainer);
    }

    @Override
    public Boolean call() throws Exception {
        RpcResponse response = new RpcResponse();
        try {
            response.setRequestId(request.getRequestId());
            Object result = handle(request);
            response.setResult(result);
            return Boolean.TRUE;
        } catch (Throwable e) {
            response.setThrowable(e);
            log.error("rpc method invoke error", e);
            return Boolean.TRUE;
        }finally {
            ctx.writeAndFlush(response);
        }
    }
}
